// pages/sign/sign.js
const app = getApp()
const db = wx.cloud.database();
const _ = db.command

let id = '';
let signStudent = [];
let allStudent = [];
let noSign = [];
let num = 0;
let number = 1000 // ，刷新次数
let sametime = 500 //刷新间隔
Page({

  /**
   * 页面的初始数据
   */


  data: {
    captchaImage: null,
    signedStudent: []
  },
  getORCode: function (_id) {
    // 调用云函数
    wx.cloud.callFunction({
      name: 'code',
      data: {
        page: "pages/text/text",
        _id: _id
      },
      success: res => {
        console.log(res)
        const base64 = wx.arrayBufferToBase64(res.result.buffer);
        console.log(base64)

        this.setData({
          captchaImage: base64
        })

      },
      fail: err => {
        console.error('[云函数] [login] 调用失败', err)
      }
    })
  },

  // 创建签到记录
  createSign() {
    // 增加签到记录
    db.collection("sign_in_history").add({
      data: {
        teacher: app.globalData.allInfo.name, //教师姓名
        teacher_openid: app.globalData.allInfo.openid, //教师openid
        subject: app.globalData.subject, //学科
        time: app.globalData.time, //时间
        timeStamp: app.globalData.timeStamp, //时间戳
        longitude: app.globalData.location.longitude, //位置经度
        latitude: app.globalData.location.latitude, //位置纬度
        classStudent: app.globalData.classStudent, //班级学生
        signedStudent: [], // 已签到学生
        noSignStudent:[]  //未签到学生
      }
    }).then(res => {
      this.getORCode(res._id)
      id = res._id
    })
  },

  // 获取签到学生信息
  getSignStudent() {
    console.log('调用刷新')
    db.collection("sign_in_history").doc(id).get().then(res => {
      console.log(res.data)
      allStudent = res.data.classStudent
      signStudent = res.data.signedStudent
      this.setData({
        signedStudent: res.data.signedStudent
      })
      this.noSignStudent()
      console.log(res.data.signedStudent)
    })
  },

  // 获取未签到学生信息
  noSignStudent() {
    noSign = []
    num += 1
    for (var i = 0; i < allStudent.length; i++) {
      var obj = allStudent[i];
      var name = obj.name;
      var student_id = obj.student_id;
      var isExist = false;
      for (var j = 0; j < signStudent.length; j++) {
        var aj = signStudent[j];
        var n = aj.name;
        var id = aj.student_id;
        if (n == name && id == student_id) {
          isExist = true;
          break;
        }
      }
      if (!isExist) {
        noSign.push(obj);
        this.setData({
          viewNoSign: noSign
        })
      }
    }
    console.log(noSign);
    this.setData({
      viewNoSign: noSign
    })
    



  },


  // 定时器执行
  timeRun() {
    var that = this
    console.log('定时器执行')
    var interval = setInterval(function () {
      db.collection("sign_in_history").doc(id).get().then(res => {
        console.log(res.data)
        allStudent = res.data.classStudent
        signStudent = res.data.signedStudent
        that.setData({
          signedStudent: res.data.signedStudent
        })
        that.noSignStudent()
        console.log(res.data.signedStudent)
      })
      db.collection("sign_in_history").doc(id).update({
        data: {
          noSignStudent:noSign
        },
        success: function (res) {
          console.log("上传未签到的学生")  
         }
        })
      num += 1
      if (num > number) {
        clearTimeout(interval);
      }
    }, sametime)
  },


  // 老师手动签到
  teacherSign(e) {
    console.log(e.currentTarget.dataset.index)
    let index = e.currentTarget.dataset.index
    db.collection("sign_in_history").doc(id).update({
      data: {
        signedStudent: _.unshift(noSign[index])
      },
      success: function (res) {
        console.log("手动添加成功")
//----------------------------------------------------------------------------------------------
// 以下代码未执行，导致无法实时更新本地数组，网络请求需要时间，切5S刷新一次，手动签到等待时间长
// 未运行原因不明，console.log()不能执行
// 解决方法，无法解决，只能在noSignStudent()中刷新本地数组，恐有bug

        noSign.splice(index, 1)
        signStudent.unshift(noSign[index])
        this.setData({
          viewNoSign: noSign,
          signedStudent :signStudent
        })
        console.log(signStudent)
        console.log(viewNoSign)
//------------------------------------------------------------------------------------------------
      }
    })
  },









  // 左划函数


  showModal(e) {
    this.setData({
      modalName: e.currentTarget.dataset.target
    })
  },
  hideModal(e) {
    this.setData({
      modalName: null
    })
  },
  gridchange: function (e) {
    this.setData({
      gridCol: e.detail.value
    });
  },
  gridswitch: function (e) {
    this.setData({
      gridBorder: e.detail.value
    });
  },
  menuBorder: function (e) {
    this.setData({
      menuBorder: e.detail.value
    });
  },
  menuArrow: function (e) {
    this.setData({
      menuArrow: e.detail.value
    });
  },
  menuCard: function (e) {
    this.setData({
      menuCard: e.detail.value
    });
  },
  switchSex: function (e) {
    this.setData({
      skin: e.detail.value
    });
  },

  // ListTouch触摸开始
  ListTouchStart(e) {
    this.setData({
      ListTouchStart: e.touches[0].pageX
    })
  },

  // ListTouch计算方向
  ListTouchMove(e) {
    this.setData({
      ListTouchDirection: e.touches[0].pageX - this.data.ListTouchStart > 0 ? 'right' : 'left'
    })
  },

  // ListTouch计算滚动
  ListTouchEnd(e) {
    if (this.data.ListTouchDirection == 'left') {
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    } else {
      this.setData({
        modalName: null
      })
    }
    this.setData({
      ListTouchDirection: null
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 

    this.createSign()
    this.timeRun()
    // this.getSignStudent()
  },


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})